﻿using CommonDevelop;
using CommonEngine;
using CommonFP;
using ManageDto;
using ManageService;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using WebAdmin.Handler;

namespace WebAdmin.Areas.Org.Controllers
{
    /// <summary>
    /// 机构管理
    /// </summary>
    [Area("Org")]
    [Route("Org/[controller]/[action]")]
    public class CompanyController : BaseController
    {
        private readonly ICompanyService _CompanyService;
        /// <summary>
        /// 构造注入
        /// </summary>
        public CompanyController(ICompanyService CompanyService)
        {
            this._CompanyService = CompanyService;
        }

        /// <summary>
        /// 视图列表
        /// </summary>
        [HttpGet]
        public ActionResult Index()
        {
            ViewBag.Title = "机构管理";
            return View();
        }

        /// <summary>
        /// 选择上级
        /// </summary>
        [HttpGet]
        public ActionResult GetSelectLayer()
        {
            ViewBag.Title = "上级机构";
            return View();
        }

        #region--Select--

        /// <summary>
        /// 机构视图列表查询（分页）
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetPageList(string pagination, string keyword)
        {
            Pagination pag = pagination.ToObject<Pagination>();
            List<CompanyDto> data = this._CompanyService.GetPageList<CompanyDto>(pag, keyword).ToList();
            var jsonData = new
            {
                rows = data,
                total = pag.total,
                page = pag.page,    //由前端配置
                records = pag.records
            };
            return this.SuccessJson(jsonData);
        }
        
        /// <summary>
        /// 树结构视图，数据源查询（不分页）
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetTreeList(string keyword)
        {
            List<CompanyDto> data = this._CompanyService.GetList<CompanyDto>(keyword).ToList();
            return this.SuccessJson(data);
        }

        #endregion

        #region--增删改--

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeAdd()
        {
            CompanyDto en = new CompanyDto();
            en.CompanyCode = this._CompanyService.BuildSeq();
            return this.SuccessJson(en);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeDelete(string keyValue)
        {
            Validation<bool> vb = this._CompanyService.Delete(keyValue);
            var ValTuple = vb.Outcome(a => a);
            if (ValTuple.Errors.IsEmpty())
                return ValTuple.result ? this.Success("操作成功") : this.Fail("操作失败");
            else
                return this.Fail(ValTuple.Errors);
        }

        [HttpPost]
        [AjaxOnly]
        public ActionResult NodeEdit(string keyValue)
        {
            var outcome = this._CompanyService.Get<CompanyDto>(keyValue);
            return outcome.Match(() => this.Fail("Null Error"),
                en => this.SuccessJson(en));
        }

        [HttpPost]
        [AjaxOnly]
        [DisableRequestSizeLimit]
        public ActionResult NodeSave([FromForm]string DataText)
        {
            CompanyDto em = PageUtility.FormMap<CompanyDto>(DataText);
            if (em == null)
                return this.Fail("表单解读失败");
            if (em.FullName.IsEmpty())
                return this.Fail("机构名称不能为空");
            if (em.CompanyCategory < 1)
                return this.Fail("请选择机构分类");
            if (em.Manager.IsEmpty())
                return this.Fail("负责人不能为空");
            if (!em.FoundedTime.HasValue)
                return this.Fail("成立时间不能为空");

            Validation<bool> vb = FP.Error("未执行");
            if (em.ModifyUserId.IsEmpty())
                vb = this._CompanyService.Add(em);
            else
                vb = this._CompanyService.Save(em);

            var ValTuple = vb.Outcome(a => a);
            if (ValTuple.Errors.IsEmpty())
                return ValTuple.result ? this.Success("操作成功") : this.Fail("操作失败");
            else
                return this.Fail(ValTuple.Errors);
        }

        #endregion

        #region--下拉数据--

        /// <summary>
        /// 获取公司分类数据
        /// </summary>
        [HttpGet]
        [AjaxOnly]
        public ActionResult GetClassification()
        {
            CompanyClassification CC = CompanyClassification.BusinessUnit;
            List<SimpleItem> Data = CC.GetEnumDescr()
                .Select(a => new SimpleItem { Seq = a.Key, Key = a.Value, Val = a.Value })
                .ToList();

            return this.SuccessJson(Data);
        }

        #endregion

    }
}